package br.nextfm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.nextfm.dao.UsuarioDao;
import br.nextfm.model.Administrador;

public class AtualizaAdministrador extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int id = Integer.parseInt(request.getParameter("id"));
		
		UsuarioDao dao = new UsuarioDao();
		Administrador administrador = dao.getAdministrador(id);
		
		request.setAttribute("administradorSelecionado", administrador);
		request.setAttribute("editar", true);
		request.setAttribute("administradores", dao.getAllAdministradores());
		request.getRequestDispatcher("administrador.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession(false);
		
		String nome = request.getParameter("nome");
		String login = request.getParameter("login");
		String senha = request.getParameter("senha");
		String email = request.getParameter("email");
		String pin = request.getParameter("pin");
		
		int id = Integer.parseInt(request.getParameter("id"));
		
		UsuarioDao dao = new UsuarioDao();
		
		Administrador administrador = dao.getAdministrador(id);
		Administrador logado = (Administrador) session.getAttribute("administrador");
		
		administrador.setEmail(email);
		administrador.setLogin(login);
		administrador.setNome(nome);
		administrador.setPin(pin);
		administrador.setSenha(senha);
		
		if (dao.update(administrador)) {
			
			if (administrador.getId() == logado.getId()) {
				session.setAttribute("administrador", administrador);
			}
		}
		
		request.setAttribute("administradores", dao.getAllAdministradores());
		request.getRequestDispatcher("administrador.jsp").forward(request, response);
		
	}

}
